{% extends "base.html" %}
{% block title %}{{ post.title }} - 论坛{% endblock %}

{% block content %}
<div class="max-w-4xl mx-auto py-6">
  <!-- 帖子内容区 -->
  <div class="bg-white rounded-lg shadow p-6 mb-6">
    <div class="flex justify-between items-start mb-4">
      <div>
        <h1 class="text-xl font-bold mb-2">{{ post.title }}</h1>
        <div class="text-sm text-gray-500">
          <span>作者: {{ post.author.username }}</span>
          <span class="mx-2">•</span>
          <span>发布于: {{ post.created_at.strftime('%Y-%m-%d %H:%M') }}</span>
          {% if post.updated_at %}
            <span class="mx-2">•</span>
            <span>最后编辑: {{ post.updated_at.strftime('%Y-%m-%d %H:%M') }}</span>
          {% endif %}
        </div>

        <!-- 点赞和评论统计 -->
        <div class="flex items-center space-x-6 mt-3">
          <!-- 点赞按钮 -->
          <button 
            id="likeBtn" 
            class="flex items-center text-gray-500 hover:text-primary transition-colors"
            onclick="handleLike({{ post.id }})"
          >
            <!-- 替换为新版空心点赞图标（未点赞状态） -->
            <i id="likeIcon" class="far fa-thumbs-up mr-1"></i>
            <span id="likeCount">{{ post.likes|length }}</span>
            <span class="ml-1">点赞</span>
          </button>
          
          <!-- 评论数量 -->
          <span class="text-gray-500">
            <!-- 替换为新版空心评论图标 -->
            <i class="far fa-comment mr-1"></i> {{ post.comments|length }} 评论
          </span>
        </div>
      </div>

      <!-- 作者操作按钮：允许 root 或原作者操作 -->
      {% if user.id == post.user_id or user.username == 'root' %}
        <div class="flex space-x-2">
          <a href="{{ url_for('edit_post', post_id=post.id) }}" class="btn-secondary text-sm px-3 py-1">
            <i class="fa fa-edit mr-1"></i>编辑
          </a>
          <form action="{{ url_for('delete_post', post_id=post.id) }}" method="POST" class="inline">
            <input type="hidden" name="csrf_token" value="{{ csrf_token_value }}">
            <button type="submit" class="btn-secondary text-sm px-3 py-1 text-danger" onclick="return confirm('确定删除这篇帖子吗？')">
              <i class="fa fa-trash mr-1"></i>删除
            </button>
          </form>
        </div>
      {% endif %}
    </div>

    <!-- 帖子正文 -->
    <div class="prose max-w-none text-gray-800 py-4 border-y">
      {{ post.content|replace('\n', '<br>')|safe }}
    </div>
  </div>

  <!-- 评论区 -->
  <div class="mb-4">
    <h2 class="text-lg font-semibold">评论 ({{ post.comments|length }})</h2>
  </div>

  <!-- 评论列表 -->
  {% if post.comments %}
    <div class="space-y-4">
      {% for comment in post.comments %}
        <div class="bg-white rounded-lg shadow p-4">
          <div class="flex justify-between items-start mb-2">
            <div class="flex items-center">
              <span class="font-medium">{{ comment.author.username }}</span>
              <span class="text-gray-400 text-sm ml-2">{{ comment.created_at.strftime('%Y-%m-%d %H:%M') }}</span>
            </div>
            
            <!-- 评论删除按钮：允许 root 或评论作者操作 -->
            {% if user.id == comment.user_id or user.username == 'root' %}
              <form action="{{ url_for('delete_comment', comment_id=comment.id) }}" method="POST" class="inline">
                <input type="hidden" name="csrf_token" value="{{ csrf_token_value }}">
                <button type="submit" class="text-danger text-sm hover:underline" onclick="return confirm('确定删除这条评论吗？')">
                  删除
                </button>
              </form>
            {% endif %}
          </div>
          <div class="text-gray-700">
            {{ comment.content|replace('\n', '<br>')|safe }}
          </div>
        </div>
      {% endfor %}
    </div>
  {% else %}
    <div class="bg-gray-50 rounded-lg p-6 text-center text-gray-500 mb-6">
      暂无评论，快来抢沙发吧～
    </div>
  {% endif %}

  <!-- 评论输入框 -->
  {% if user.is_authenticated %}
    <div class="bg-white rounded-lg shadow p-6 mt-6">
      <form method="POST" class="space-y-3">
        <input type="hidden" name="csrf_token" value="{{ csrf_token_value }}">
        <textarea 
          name="content" 
          rows="3" 
          placeholder="分享你的看法..." 
          class="form-input w-full resize-none"
          required
        ></textarea>
        <div class="flex justify-end">
          <button type="submit" class="btn-primary">
            <i class="fa fa-comment mr-2"></i>提交评论
          </button>
        </div>
      </form>
    </div>
  {% else %}
    <div class="bg-gray-50 rounded-lg p-6 mt-6 text-center">
      <a href="{{ url_for('login', next=url_for('forum_post', post_id=post.id)) }}" class="text-primary hover:underline">
        登录后可发表评论
      </a>
    </div>
  {% endif %}
</div>
{% endblock %}

{% block scripts %}
<!-- 点赞功能脚本（保持不变） -->
<script>
// 页面加载时初始化点赞状态
document.addEventListener('DOMContentLoaded', function() {
    const postId = {{ post.id }};
    const userId = {{ user.id if user.is_authenticated else 'null' }};
    
    // 已登录用户检查是否已点赞
    if (userId) {
        const likedUsers = [{% for like in post.likes %}{{ like.user_id }},{% endfor %}];
        if (likedUsers.includes(userId)) {
            document.getElementById('likeIcon').className = 'fa fa-thumbs-up mr-1 text-primary';
        }
    }
});

// 处理点赞/取消点赞
function handleLike(postId) {
    {% if not user.is_authenticated %}
        alert('请先登录才能点赞');
        return;
    {% endif %}

    const btn = document.getElementById('likeBtn');
    const icon = document.getElementById('likeIcon');
    const countElem = document.getElementById('likeCount');
    
    btn.disabled = true;
    icon.className = 'fa fa-spinner fa-spin mr-1';

    fetch(`/forum/post/${postId}/like`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRFToken': document.querySelector('meta[name="csrf-token"]').content
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.status === 'success') {
            countElem.textContent = data.like_count;
            icon.className = data.is_liked 
                ? 'fa fa-thumbs-up mr-1 text-primary' 
                : 'fa fa-thumbs-o-up mr-1';
        } else {
            alert('操作失败：' + data.message);
            icon.className = icon.className.includes('thumbs-up') 
                ? 'fa fa-thumbs-up mr-1 text-primary' 
                : 'fa fa-thumbs-o-up mr-1';
        }
        btn.disabled = false;
    })
    .catch(error => {
        console.error('点赞请求失败:', error);
        alert('网络错误，请稍后再试');
        btn.disabled = false;
        icon.className = icon.className.includes('thumbs-up') 
            ? 'fa fa-thumbs-up mr-1 text-primary' 
            : 'fa fa-thumbs-o-up mr-1';
    });
}
</script>
{% endblock %}